package controls

import (
	"io"
	"log"
	"mime/multipart"
	"server/types"
	"server/utils"

	"github.com/gin-gonic/gin"
)

func ToWEBP(context *gin.Context) {
	var err error
	var upload *multipart.FileHeader
	var f multipart.File
	var n int
	var output []byte
	data := make([]byte, 1024*1024*20)
	//获取参数
	var params types.ReqToWEBP
	err = context.Bind(&params)
	if err != nil {
		log.Println(err)
		return
	}
	//获取上传文件信息
	upload, err = context.FormFile("image")
	if err != nil {
		log.Println(err)
		return
	}
	if upload.Size > 1024*1024*20 {
		log.Println("file size too large")
		return
	}
	//读取文件
	f, err = upload.Open()
	if err != nil {
		log.Println(err)
		return
	}
	defer f.Close()
	n, err = f.Read(data)
	if err != nil {
		log.Println(err)
		return
	}

	output, err = utils.ToWebp(data[:n], upload.Filename, params.Quality, params.Lossless, params.Exact)
	context.Header("Content-Type", "application/octet-stream")
	context.Stream(func(w io.Writer) bool {
		_, err = w.Write(output)
		return err != nil
	})
}
